﻿using System;
using System.Linq;
using log4net;
using Reactor.Configuration;
using Reactor.ServiceGrid;

namespace Reactor.Customization
{
    public class InitializationCustomizationManager : CustomizationManagerBase<ICustomizeReactorInitialization>
    {
        private static ILog _log;

        /// <summary>
        /// This is used for the bus customizer to pickup and use for the primary endpoint name. It is needed 
        /// for proper bus initialization.
        /// </summary>
        public static string PrimaryEndpointName;

        /// <summary>
        /// ServiceIdentifier being proposed as the service to create upon initialization.
        /// </summary>
        public static ServiceIdentifier ProposedServiceIdentifier;

        /// <summary>
        /// Service Instance Identifier being proposed for the service to be created 
        /// upon initialization. For Reactor Services, not Cores.
        /// </summary>
        public static Guid ServiceInstanceIdentifier;

        /// <summary>
        /// Initializes a new instance of the <see cref="InitializationCustomizationManager"/> class.
        /// </summary>
        public InitializationCustomizationManager() : base(AppDomain.CurrentDomain.BaseDirectory)
        {
            _log = LogManager.GetLogger(GetType());
        }

        /// <summary>
        /// Runs all customers found by this instance.
        /// </summary>
        public override void RunAll()
        {
            // Sort customizers by execution order
            Customizers = Customizers.OrderBy(i => i.ExecutionOrder).ToList();

            foreach (var item in Customizers)
            {
                if (_log.IsDebugEnabled) _log.DebugFormat("Executing initialization customizer: {0}", item.GetType().FullName);
                item.InitializeReactor();
            }
        }
    }
}
